package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/7/11.
 */
public class JsonUtil {

    private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);

    /**
     * 将json字符串转为map（包括子、孙对象都自动转为map）
     * @param json
     * @return
     * @throws IOException
     * @throws JsonProcessingException
     */
    public static Map<String, Object> jsonToMap(String json) throws IOException {
        try {
            if (StringUtils.isBlank(json)) return new HashMap<>();

            return JSON.parseObject(json);
        }catch (Exception ex){
            throw new IOException(ex.getMessage(), ex);
        }
    }

    /**
     * 将json字符串转为map（包括子、孙对象都自动转为map）
     * @param json
     * @return
     * @throws IOException
     * @throws JsonProcessingException
     */
    public static Map<String, Object> jsonToMap2(String json) {
        try {
            return jsonToMap(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Deprecated
    public static <T> T toBean(String json,Class<T> tClass){
        return fromJson(json, tClass);
    }
    public static <T> T fromJson(String json,Class<T> tClass){
        try {
            return JSONObject.parseObject(json, tClass);
        } catch (Exception e) {
            return null;
        }
    }

    public static String toJson(Object obj){
        if(obj == null) return null;
        try {
            return JSON.toJSONString(obj);
        }catch(Exception ex){
            log.debug("Ojbect to Json error: {}", ex.getMessage());
            return null;
        }
    }
    public static String toJson(Object obj, String subFieldName, Object subFieldObject){
        Map<String,Object> map = new HashMap<>();
        map.put(subFieldName, subFieldObject);
        return toJson(obj, map);
    }
    public static String toJson(Object obj, Map<String, Object> subFields){
        try {
            Map<String, Object> map = jsonToMap(toJson(obj));
            map.putAll(subFields);
            return JSON.toJSONString(map);
        }catch(Exception ex){
            return null;
        }
    }
}
